############# ModelViewSet编写视图接口 ###################
### 数据被封装在res.results中
import logging

# from rest_framework import viewsets
# from .models import Student
# from .serializers import StudentSerializer
# from django_filters.rest_framework import DjangoFilterBackend
# from rest_framework import filters
#
# class StudentViewSet(viewsets.ModelViewSet):
#     queryset = Student.objects.all().order_by('id')
#     serializer_class = StudentSerializer
#     filter_backends = [DjangoFilterBackend, filters.SearchFilter]
#     filterset_fields = ['gender', 'phone']
#     search_fields = ['^name']

############# APIView编写视图接口 ###################
### list-get数据res

from django.core.cache import cache
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework.filters import SearchFilter
from django_filters.rest_framework import DjangoFilterBackend
from django.http import Http404
from .models import Student
from .pagination import StandardPagination
from .serializers import StudentSerializer


class StudentListAPIView(APIView):
    serializer_class = StudentSerializer
    filter_backends = [DjangoFilterBackend, SearchFilter]
    filterset_fields = ['gender']
    search_fields = ['^name', 'phone']  # '^' 表示以搜索词开头（区分大小写）
    pagination_class = StandardPagination

    def get_queryset(self):
        return Student.objects.all().order_by('id')

    def filter_queryset(self, queryset):
        # 依次应用所有过滤后端
        for backend in self.filter_backends:
            queryset = backend().filter_queryset(self.request, queryset, self)
        return queryset

    def get(self, request, *args, **kwargs):
        ####### 暂时取消Redis缓存 #########
        ## 将学生列表数据加入Redis缓存
        # cache_key = request.get_full_path() # 缓存key为请求路径
        # cached_data = cache.get(cache_key)
        # if cached_data:
        #     print("从缓存中获取数据,cache_key:", cache_key)
        #     return Response(cached_data)
        
        queryset = self.filter_queryset(self.get_queryset())
        page = self.pagination_class()
        page_qs = page.paginate_queryset(queryset, request, view=self)
        if page_qs is not None:
            serializer = StudentSerializer(page_qs, many=True)
            response_data = page.get_paginated_response(serializer.data)
            # cache.set(cache_key, response_data.data, timeout=60*5)  # 缓存5分钟
            return response_data
        serializer = StudentSerializer(queryset, many=True)
        response_data = Response(serializer.data)
        # cache.set(cache_key, response_data.data, timeout=60*5)  # 缓存5分钟
        return response_data

    def post(self, request):
        serializer = self.serializer_class(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

class StudentDetailAPIView(APIView):
    serializer_class = StudentSerializer

    def get_object(self, pk):
        try:
            return Student.objects.get(pk=pk)
        except Student.DoesNotExist:
            raise Http404

    def get(self, request, pk):
        student = self.get_object(pk)
        serializer = self.serializer_class(student)
        return Response(serializer.data)

    def put(self, request, pk):
        student = self.get_object(pk)
        serializer = self.serializer_class(student, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    def patch(self, request, pk):
        student = self.get_object(pk)
        serializer = self.serializer_class(student, data=request.data, partial=True)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    def delete(self, request, pk):
        student = self.get_object(pk)
        student.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)